package com.stox.core.ui.swing.wrapper;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.swing.Action;

import com.stox.core.ui.swing.util.SwingUtil;
import com.stox.design.Initializable;
import com.stox.design.Ordered;
import com.stox.resources.image.ImageIconLoader;

public abstract class JMenu extends javax.swing.JMenu implements Initializable<Void, Void> {
	private static final long serialVersionUID = -5609437172102237960L;
	
	public void orderItems(){
		List<javax.swing.JMenuItem> jMenuItems = new ArrayList<javax.swing.JMenuItem>();
		for(int i = 0; i < getItemCount(); i++){
			jMenuItems.add(getItem(i));
		}
		if(jMenuItems.size() > 1){
			List<Ordered> orderedList = new ArrayList<Ordered>(jMenuItems.size());
			for(javax.swing.JMenuItem item : jMenuItems){
				if (item instanceof Ordered) {
	                  orderedList.add((Ordered)item);
	              }
			}
			
			if(!orderedList.isEmpty()){
				 Collections.sort(orderedList, OrderComparator.instance);
			}
			removeAll();
			for(Ordered ordered : orderedList){
				add((javax.swing.JMenuItem)ordered);
			}
			jMenuItems.removeAll(orderedList);
			for(javax.swing.JMenuItem item : jMenuItems){
				add(item);
			}
		}
	}
	
	@Override
	public int getOrder() {
		return 0;
	}
	
	@Override
	public Void invoke(Void payload) {
		orderItems();
		return null;
	}
	
	private void init(){
		SwingUtil.initializeWidget(this);
	}
	
	public JMenu() {
		super();
		init();
	}

	public JMenu(Action a) {
		super(a);
		init();
	}

	public JMenu(String s, boolean b) {
		super(s, b);
		init();
	}

	public JMenu(String s) {
		super(s);
		init();
	}
	
	public JMenu(String name, int mnemonic, String iconPath){
		super(name);
		setMnemonic(mnemonic);
		setIcon(ImageIconLoader.loadImageIcon(iconPath));
	}

}
